import React, {useEffect, useState} from 'react';
import { Form, Button,TreeSelect,Upload,Input, Modal,Row,message, Col,InputNumber,Select} from 'antd';
import { connect } from 'umi';
import {UploadOutlined} from '@ant-design/icons';
import {getUploadUrl} from '@/utils/upload'
import SelectUserModal from "@/pages/components/SelectUserModal";
import ImportUser from './ImportUser';
import AllocationTable from "./AllocationTable";
import {getPerformanceRatioById} from '../service';
import {getEmployessInfoByCode} from "@/pages/ScoreOf360/service";
import {resultSum} from "@/utils/utils";
import {assessGradeTypeList} from '@/utils/constant';

const FormItem = Form.Item;
const {TextArea} = Input;
const formLayout = {
  labelCol: { span: 7 },
};
const colStyle = {
  xl: 12,
  lg: 12,
  md: 12,
  sm: 12,
  xs: 12,
};

let uploadedFiles = [];
const { Option } = Select;

const BatchAllocationForm = (props) => {
  const { onSubmit, onCancel, loading,visible,currentUser} = props;
  const [form] = Form.useForm();
  const [fileUploadUrls,setFileUploadUrls] = useState([]);
  const [fileName, setFileName] = useState(null);
  const [userModalVisible, setUserModalVisible] = useState(false);
  const [scaleInfo,setScaleInfo] = useState({});
  const [enterNum,setEnterNum] = useState(0);
  const [type,setType] = useState(null);
  const [importVisible, setImportVisible] = useState(false);
  const [tempRecord,setTempRecord] = useState({});

  const [tempData,setTempData] = useState({});

  const fileList = {
    name: 'file',
    multiple: true,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: uploadedFiles,
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls,res.file.response ]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1){
        urls.splice(index, 1);
        setFileUploadUrls(urls);
      }
    },
  };

  useEffect(() => {
    if(currentUser && visible){
      getPerformanceRatioById(2).then(res => {
        setScaleInfo(res);
      });
    }
  }, [visible]);

  const computeNum = () => {
    const fieldsValue = form.getFieldsValue();
    let t = {};
    t.percentageA = fieldsValue.percentageA?.length || 0;
    t.percentageBPlus = fieldsValue.percentageBPlus?.length || 0;
    t.percentageB = fieldsValue.percentageB?.length || 0;
    t.percentageC = fieldsValue.percentageC?.length || 0;
    t.percentageD = fieldsValue.percentageD?.length || 0;
    setTempRecord(t);
  };

  const onFormCancel = () => {
    form.resetFields();
    uploadedFiles = [];
    setFileUploadUrls([]);
    onCancel();
  };

  const handleSubmit = async () => {
    if(resultSum(tempRecord) !== enterNum){
      message.error("分配数量不一致，请核实后再提交！");
      return;
    }
    const fieldsValue = await form.validateFields();
    // form.resetFields();
    // let fileUploadUrlsStr = '';
    // fileUploadUrls.forEach(item => {
    //   if (item){
    //     if (fileUploadUrlsStr === ''){
    //       fileUploadUrlsStr += item;
    //     }else {
    //       fileUploadUrlsStr += ',' + item;
    //     }
    //   }
    // });
    // onSubmit({
    //   ...fieldsValue,
    //   uploadFile:fileUploadUrlsStr,
    // });
    uploadedFiles = [];
    setFileUploadUrls([]);
  };

  const setRaterData = (dataList) => {
    let temp = {...tempData};
    switch (type) {
      case 'percentageA':
        temp.percentageA = Array.from(new Set([...temp.percentageA || [],...dataList]));
        break;
      case 'percentageBPlus':
        temp.percentageBPlus = Array.from(new Set([...temp.percentageBPlus || [],...dataList]));
        break;
      case 'percentageB':
        temp.percentageB = Array.from(new Set([...temp.percentageB || [],...dataList]));
        break;
      case 'percentageC':
        temp.percentageC = Array.from(new Set([...temp.percentageC || [],...dataList]));
        break;
      case 'percentageD':
        temp.percentageD = Array.from(new Set([...temp.percentageD || [],...dataList]));
        break;
    }
    setTempData(temp);
  };

  const confirmSelectUser = (infos) => {
    if (infos.length>0) {
      let obj = {};
      let originalList = form.getFieldValue(type);
      originalList = originalList || [];
      let needsUserList = new Set(infos.map(info => ({oid: info.oid, name: info.name})));
      let needsUserOidList = infos.map(info =>(info.oid));
      setRaterData(needsUserList);
      obj[type] = Array.from(new Set([...originalList,...needsUserOidList]));
      form.setFieldsValue(obj);
      computeNum();
      setUserModalVisible(false);
      setType(null);
    } else {
      message.error('请选择人员!')
    }
  };

  const showSelectUserModal = (type) => {
    setUserModalVisible(true);
    setType(type);
  };

  const cancelImport = () => {
    setImportVisible(false);
    setType(null);
  };

  const openImportModal = (type) => {
    setImportVisible(true);
    setType(type);
  };

  const importPerson = (codes)=> {
    setImportVisible(false);
    getEmployessInfoByCode(codes).then(res => {
      message.success(res.notFoundStr);
      if (res.employeeInfoEntityList && res.employeeInfoEntityList.length>0){
        let obj = {};
        let originalList = form.getFieldValue(type);
        originalList = originalList ? originalList : [];
        let personList = res.employeeInfoEntityList.map(item=>({name: item.name, oid: item.oid}));
        setRaterData(personList);
        obj[type] = Array.from(new Set([...originalList,...personList.map(item => item.oid)]));
        form.setFieldsValue(obj);
        computeNum();
      }
      setType(null);
    })
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="oprationId" label="单位名称">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="oprationName" label="单位绩效">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="orgName" label="考核年度" >
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="unitName" label="考核周期" >
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobName" label="单位总人数">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="number" label="参加考核人数" rules={[{required: true, message: '参加考核人数不能为空'}]}>
              <InputNumber style={{width: '100%'}} placeholder="请输入考核人数" min={0} onChange={(num) => setEnterNum(num || 0)}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="reason" label="绩效说明">
              <TextArea rows={2}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="uploadFile" label="上传附件" rules={[{required: true, message: '附件不能为空'}]}>
              <Upload {...fileList}>
                <Button>
                  <UploadOutlined/> 点击上传附件
                </Button>
              </Upload>
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem name="list">
              <AllocationTable scaleInfo={scaleInfo} tempRecord={tempRecord} enterNum={enterNum}/>
            </FormItem>
          </Col>
          {
            assessGradeTypeList?.map((item, index) => {
              const temp = scaleInfo;
              return (temp && temp[item.value] !== 0) && <Col span={24} style={{display: 'flex'}} key={index}>
                <Form.Item labelCol={{span: 7}} style={{width: '66.5%'}} name={item.value} label={item.label}>
                  <Select mode="multiple" onChange={computeNum}>
                    {tempData[item.value]?.map(item => (<Option key={item.oid} value={item.oid}>{item.name}</Option>))}
                  </Select>
                </Form.Item>
                <Button style={{marginLeft: '5px'}} onClick={() => showSelectUserModal(item.value)}>添加</Button>
                <Button loading={false} type='primary' style={{marginLeft: '5px'}} onClick={() => openImportModal(item.value)}>批量</Button>
              </Col>
            })
          }
          <Col span={24} style={{display: 'flex',justifyContent: 'center',marginBottom: '24px'}}>
            <Button type="link">导入模板下载</Button>
            <Button type="primary" style={{margin:'0 6%'}}>完整名单导入</Button>
            <Button type="link">完整名单导出</Button>
          </Col>
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" onClick={() => handleSubmit()} loading={loading}>提交</Button>
      </>
    )
  };

  return (
    <Modal
      width={'70%'}
      destroyOnClose
      centered
      title={`批量分配`}
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
        <SelectUserModal
          selectType={1}
          visible={userModalVisible}
          handleOk={confirmSelectUser}
          handleCancel={()=>setUserModalVisible(false)}
        />
        <ImportUser
          visible={importVisible}
          onSubmit={importPerson}
          onCancel={cancelImport}
        />
      </Form>
    </Modal>
  )
};

export default connect(({user}) => ({
  currentUser: user.currentUser,
}))(BatchAllocationForm);
